<template>
  <div>
    <el-row>
      <el-col :span="24">
        <el-card>
          <el-form :inline="true" :model="formInline" class="demo-form-inline">
            <el-form-item label="车位编号">
              <el-input v-model="formInline.spaceCode"></el-input>
            </el-form-item>
            <el-form-item label="停车场编号">
              <el-input v-model="formInline.lotCode"></el-input>
            </el-form-item>
            <el-form-item label="缴费金额">
              <el-input v-model="formInline.cost"></el-input>
            </el-form-item>
            <el-form-item label="每小时费率">
              <el-input v-model="formInline.hourlyRate"></el-input>
            </el-form-item>
            <el-form-item label="缴费状态">
              <el-select v-model="formInline.isAvailable" placeholder="请选择">
                <el-option label="全部" value=""></el-option>
                <el-option label="未缴费" :value="0"></el-option>
                <el-option label="已缴费" :value="1"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="入场时间">
              <el-config-provider :locale="locale">
                <el-date-picker
                  v-model="formInline.startTime"
                  type="date"
                  placeholder="选择日期时间"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                  :locale="locale"
                />
              </el-config-provider>
            </el-form-item>
            <el-form-item label="出场时间">
              <el-config-provider :locale="locale">
                <el-date-picker
                  v-model="formInline.endTime"
                  type="date"
                  placeholder="选择日期时间"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                  :locale="locale"
                />
              </el-config-provider>
              <el-form-item label="备注">
                <el-input v-model="formInline.remark"></el-input>
              </el-form-item>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="fetchData">查询</el-button>
              <el-button type="info" @click="resetQueryData">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
        <el-card v-loading="isLoading" element-loading-text="加载中...">
          <template #header>
              <div>
              <h3>停车缴费记录</h3>
              </div>
          </template>
          <el-table :data="tableData" border style="width: 100%" @selection-change="handleSelectionChange2">
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column label="序号" width="70" align="center" style = "background-color :black">
              <template #default="scope">
                <div class="serial-number">
                  {{ (currentPage - 1) * pageSize + scope.$index + 1 }}
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="id" label="入场记录id" v-if="false"></el-table-column>
            <el-table-column prop="lotCode" label="停车场编号" width="120"></el-table-column>
            <el-table-column prop="spaceCode" label="车位编号" width="120"></el-table-column>
            <el-table-column prop="cost" label="缴费金额(元)" width="120"></el-table-column>
            <el-table-column prop="hourlyRate" label="每小时费率(元/时)" width="150"></el-table-column>
            <el-table-column prop="memberDiscount" label="会员折扣" width="150"></el-table-column>
            <el-table-column prop="status" label="缴费状态" width="150"></el-table-column>
            <el-table-column prop="startTime" label="入场时间" width="200"></el-table-column>
            <el-table-column prop="endTime" label="出场时间" width="200"></el-table-column>
            <el-table-column prop="userId" label="用户ID" v-if="false"></el-table-column>
            <el-table-column prop="remark" label="备注" width="250"></el-table-column>
            <el-table-column label="操作">
              <template #default="scope">
                <el-button 
                  size="success" 
                  :disabled = "scope.row.status !== '未缴费' || scope.row.endTime === null || scope.row.endTime === ''" 
                  @click="handlePayment(scope.row)"
                >
                  缴费
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <div style="margin-top: 20px; margin-bottom: 20px; text-align: right; float: right;">
            <el-config-provider :locale="locale">
              <el-pagination
                background
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
                :current-page="currentPage"
                :page-size="pageSize"
                :page-sizes="[10, 20, 50, 100]"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              ></el-pagination>
            </el-config-provider>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>
<script setup>
import zhCn from 'element-plus/es/locale/lang/zh-cn'; 
import { ref, onMounted, watch } from 'vue';
import axios from 'axios';
import { ElMessageBox, ElMessage } from 'element-plus'
import { useRoute } from 'vue-router';

const route = useRoute();

const formInline = ref({
  id: '',
  lotCode: '',
  isAvailable: '',
  userId: '',
  isMemberOnly: '',
  code: ''
});
const tableData = ref([]);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);
const locale = zhCn;
const isLoading = ref(false);

const api = axios.create({
    baseURL:'http://localhost:8092',
    headers: {
        'Authorization': `${localStorage.getItem('token')}`
    }
})
onMounted(() => {
  payReturn();
});

// 监听路由变化, 避免在其他页面修改影响本页面数据时不自动刷新的情况
watch(() => route.path, (newPath) => {
  if(newPath === '/user/PaymentManagement') {
    console.error("刷新PaymentManagement");
    fetchData();
  }
});

const fetchData = async () => {
  isLoading.value = true;
  const params = {
      ...formInline.value,
      userId: localStorage.getItem("id"),
      pageIndex: currentPage.value,
      pageSize: pageSize.value
    };
  Object.keys(params).forEach(key => (params[key] === '' || params[key] === null) && delete params[key]);
  try {
    const response = await api.get('/api/v1/parking-record/parking-record-info', { params });
      if (response.data.code === "200") {
        if(response.data.data != null){
          tableData.value = response.data.data.records;
          total.value = response.data.data.total;
        } else {
          tableData.value = [];
          total.value = 0;
        }
        // 遍历tableData中的每一项，查询停车记录对应的停车场信息
        for (let i = 0; i < tableData.value.length; i++) {
          const parkingSpace = tableData.value[i];
          const parkingLotResponse = await api.get('/api/v1/parking-lot/parking-lot-info', {
            params: { lotCode: parkingSpace.lotCode }
          });
          if(parkingLotResponse.data.code === "200" && parkingLotResponse.data.data) {
            const parkingLotInfo = parkingLotResponse.data.data.records[0];
            // 查询收费策略信息
            const feeScheduleResponse = await api.get('/api/v1/fee-schedule/fee-schedule-info', {
              params: { feeScheduleCode: parkingLotInfo.feeScheduleCode }
            });
            if(feeScheduleResponse.data.code === "200" && feeScheduleResponse.data.data) {
              const feeScheduleInfo = feeScheduleResponse.data.data.records[0];
              tableData.value[i].memberDiscount = feeScheduleInfo.memberDiscount;
            }
          }
        }
      } else {
        ElMessage({
          title: '错误',
          message: '获取停车记录失败！' + response.data.message,
          type: 'error',
          showClose: false
        });
      }
  } catch (error) {
    ElMessage({
      title: '错误',
      message: '获取停车记录失败！' + error.message,
      type: 'error',
      showClose: false
    });
  } finally {
    isLoading.value = false;
  }
};

const handlePayment = async (row) => {
  try {
    let processedCost = row.cost;
    const responseUser = await api.get('/api/v1/user/user-info', {
          params: { userId: localStorage.getItem("id") }
        });
    // 判断是否是会员，计算会员价
    if(responseUser.data.code === "200" && responseUser.data.data != null){
      const userInfo = responseUser.data.data.records[0];
      if(userInfo.role === '会员'){
        processedCost = row.cost * row.memberDiscount;
      }
    } 
    await ElMessageBox.confirm(
      `确认是否进行缴费: ` + processedCost + `元`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: true
      }
    );
    
    const response = await api.post("/api/v1/pay/pay-parking-record", {
      id: row.id,
      cost: processedCost
    });
    let resp = response.data;
    if (resp.code === "200") {
      // 创建一个唯一的容器来放置表单
      const containerId = 'paymentFormContainer';
      let formContainer = document.getElementById(containerId);
      if (!formContainer) {
        formContainer = document.createElement('div');
        formContainer.id = containerId;
        document.body.appendChild(formContainer);
      } else {
        formContainer.innerHTML = ''; // 清空可能存在的旧表单
      }

      formContainer.innerHTML = resp.data; // 插入后端返回的form 表单字符串

      // 查找具有特定ID或类名的表单，并提交
      const form = formContainer.querySelector('form');
      if (form) {
        form.submit();
      } else {
        console.error("找不到要提交的表单");
      }
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage({
        message: '缴费失败！' + error.message,
        type: 'error'
      });
    } else {
      ElMessage({
        type: 'info',
        message: '已取消缴费'
      });
    }
  }
};

const payReturn = () => {
  // 使用 route.query 来获取查询参数
  if (route.query && route.query.out_trade_no) {
    const out_trade_no = route.query.out_trade_no;
    api.put("/api/v1/parking-record/parking-record-info", {
      id: out_trade_no,
      status: '已缴费'
    }).then((response) => {
      const resp = response.data;
      if (resp.code === "200") {
        ElMessage({
          message: "交易号：" + out_trade_no + "：缴费成功",
          type: 'success'
        });
        fetchData();
      } else {
        ElMessage({
          message: resp.msg,
          type: 'error'
        });
      }
    }).catch(error => {
      console.error('支付回调处理失败:', error);
      ElMessage({
        message: '支付回调处理失败！' + error.message,
        type: 'error'
      });
    });
  }
};
const handleCurrentChange = (page) => {
  currentPage.value = page;
  fetchData();
};
const handleSizeChange = (size) => {
  pageSize.value = size;
  fetchData();
};

const resetQueryData = () =>{
  formInline.value = {
    id: '',
    lotCode: '',
    isAvailable: '',
    userId: '',
    isMemberOnly: '',
    code: ''
  };
  fetchData();
}

// 页面加载时自动获取数据
fetchData();
</script>

<style scoped>
.admin-dashboard {
  height: 100vh;
}
.el-container {
  height: 100%;
}
.el-aside {
  background-color: #f8f9fa;
}
.el-main {
  padding: 20px;
}
.el-card {
  margin-bottom: 20px; /* 卡片底部外边距 */
}
/* 确保鼠标悬停时的交互效果不变 */
.el-table .cell {
  pointer-events: none; /* 禁用单元格内的点击事件以保留默认的行选中效果 */
}
.el-select {
  width: 180px; /* 设置你希望的宽度 */
}
</style>